package Task20;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

public final class Factory{
	
	private static Map<String,Class<?>> mapCommandClasses;
	private static Map<String,modelInterface>Instances;
	private static boolean createMap = false;
	
	//method for create the map, performed once
	public static void form_Map() throws Exception, SecurityException, IllegalAccessException, NoSuchFieldException{
		if(!createMap){
		mapCommandClasses = new HashMap<String,Class<?>>();
		Instances = new HashMap<String,modelInterface>();
		for (Class<?> subclass : new Model().getClass().getClasses()) { 
			String Key = (String)subclass.getConstructor(Model.class).
					newInstance(new Model()).getClass().getDeclaredField("key").get(null);
			mapCommandClasses.put(Key,subclass);
			Instances.put(Key,null);
		}
		createMap=true;
		}
	}
	//realization method for getting the new instance, but previously check him exist (singleton)
	public static modelInterface getInstance(String[] args) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException{
		String command = args[0];
		if (Instances.get(command)==null){
		modelInterface instance = (modelInterface) mapCommandClasses.
				get(command).getConstructor(Model.class).newInstance(new Model());
		Instances.put(command,instance);
		return instance;
		}
		else return Instances.get(command);
	}
}
